package com.wen.ucenter.controller;

import com.alibaba.nacos.common.util.UuidUtils;
import com.google.gson.Gson;
import com.wen.commonutils.GuLiUtils;
import com.wen.servicebase.exception.BusinessException;
import com.wen.ucenter.entity.Member;
import com.wen.ucenter.service.MemberService;
import com.wen.ucenter.util.HttpClientUtils;
import com.wen.ucenter.util.WeiXinProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author：Win
 * @Date: 2021/6/15 16:05
 * @Description:
 */
@Controller
@RequestMapping("/api/ucenter/wx")
public class WeiXinApiController {
    @Resource
    private MemberService memberService;
    private static final Logger LOGGER = LoggerFactory.getLogger(WeiXinApiController.class);

    /**
     * 生成微信扫描二维码
     *
     * @return 重定向至微信地址
     */

    @GetMapping("login")
    public String getQrCode() {
        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        // 回调地址
        String redirectUrl = WeiXinProperties.REDIRECT_URL; //获取业务服务器重定向地址
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8"); //url编码
        } catch (UnsupportedEncodingException e) {
            throw new BusinessException(e.getMessage());
        }

        // 防止csrf攻击（跨站请求伪造攻击）
        //String state = UUID.randomUUID().toString().replaceAll("-", "");//一般情况下会使用一个随机数
        String state = UuidUtils.generateUuid().replace("-", "");//为了让大家能够使用我搭建的外网的微信回调跳转服务器，这里填写你在ngrok的前置域名

        // 采用redis等进行缓存state 使用sessionId为key 30分钟后过期，可配置
        //键："wechar-open-state-" + httpServletRequest.getSession().getId()
        //值：satte
        //过期时间：30分钟

        //生成qrcodeUrl
        String qrcodeUrl = String.format(baseUrl, WeiXinProperties.APP_ID, redirectUrl, state);

        return "redirect:" + qrcodeUrl;
    }

    /**
     * 获取扫描人信息,并添加到数据库
     *
     * @param code  临时票据
     * @param state 跨域防伪标志
     * @return
     */
    @GetMapping("callback")
    public String callback(@RequestParam("code") String code, @RequestParam("state") String state) {

        //得到授权临时票据code
        //从redis中将state获取出来，和当前传入的state作比较
        //如果一致则放行，如果不一致则抛出异常：非法访问
        //向认证服务器发送请求换取access_token
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";

        String accessTokenUrl = String.format(baseAccessTokenUrl,
                WeiXinProperties.APP_ID,
                WeiXinProperties.APP_SECRET,
                code);

        String result;
        try {
            result = HttpClientUtils.get(accessTokenUrl);
            LOGGER.info("accessToken=============" + result);
        } catch (Exception e) {
            throw new BusinessException("获取access_token失败");
        }

        //解析json字符串
        Gson gson = new Gson();
        Map map = gson.fromJson(result, HashMap.class);
        String accessToken = (String) map.get("access_token");
        String openid = (String) map.get("openid");

        //查询数据库当前用用户是否曾经使用过微信登录
        Member member = memberService.getByOpenid(openid);
        if (member == null) {
            LOGGER.info("新用户注册");
            //访问微信的资源服务器，获取用户信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
            String resultUserInfo;
            try {
                resultUserInfo = HttpClientUtils.get(userInfoUrl);
                LOGGER.info("resultUserInfo==========" + resultUserInfo);
            } catch (Exception e) {
                throw new BusinessException("获取用户信息失败");
            }

            //解析json
            Map<String, Object> mapUserInfo = gson.fromJson(resultUserInfo, HashMap.class);
            String nickname = (String) mapUserInfo.get("nickname");
            String headImgUrl = (String) mapUserInfo.get("headimgurl");
            double sex = (double) mapUserInfo.get("sex");
            System.out.println(sex);
            //向数据库中插入一条记录
            member = new Member();
            member.setNickname(nickname);
            member.setOpenid(openid);
            member.setAvatar(headImgUrl);
            member.setSex((int) sex);
            memberService.save(member);
        }
//      因为cookie不能实现跨域访问,所以使用jwt根据member对象生成字符串
        String jwtToken = GuLiUtils.getJwtToken(member.getId(), member.getNickname());
//      最后使用路径传递参数
        return "redirect:http://localhost:3000?token=" + jwtToken;
    }
}
